using System.IO;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;
using Universe.Remoting.Sinks;

namespace Universe.Remoting.Extensions
{
    class TrafficClientSink : BaseCustomSink
    {
        private string _typeName;
        private string _methodName;
        private long sent;
        protected override void ProcessRequest(IMessage message, ITransportHeaders headers, ref Stream stream, ref object state)
        {
            if (Info.GetMessageInfo(message, out _typeName, out _methodName))
            {
            }

            if (stream != null && stream.CanSeek)
                sent = stream.Length;
        }

        protected override void ProcessResponse(IMessage message, ITransportHeaders headers, ref Stream stream, object state)
        {
            if (stream != null)
            {
                if (_typeName != null && _methodName != null)
                {
                    MemoryStream copy = new MemoryStream();
                    byte[] buffer = new byte[1024];
                    while (true)
                    {
                        int n = stream.Read(buffer, 0, buffer.Length);
                        if (n <= 0)
                            break;

                        copy.Write(buffer, 0, n);
                    }

                    long recieved = copy.Length;
                    stream = copy;
                    stream.Position = 0;

                    TrafficStatisticConfiguration.Client.UpdateTotal(1, sent, recieved);
                    TrafficStatisticConfiguration.Client.Update(_typeName, _methodName, sent, recieved);
                }
            }
        }
    }
}
